package com.ruoyi.common.utils;

import java.util.concurrent.atomic.AtomicLong;

/**
 * @ClassName AutoCreateUtil
 * @Description
 * @Author sizegang
 * @Date2025/4/19 21:14
 **/
public class AutoCreateNumberUtil {
    private static final AtomicLong LAST_TIMESTAMP = new AtomicLong(-1L);

    /**
     * 生成唯一的编号
     *
     * @return 编号
     */
    public static String generateNo(String prefix, int RANDOM_LENGTH) {
        long timestamp = System.currentTimeMillis();
        long lastTimestamp = LAST_TIMESTAMP.get();

        // 确保时间戳是递增的
        if (timestamp <= lastTimestamp) {
            timestamp = waitNextMillis(lastTimestamp);
        }

        LAST_TIMESTAMP.set(timestamp);

        // 生成随机数部分
        String randomPart = generateRandomPart(RANDOM_LENGTH);

        // 组合时间戳和随机数
        return prefix + timestamp + randomPart;
    }

    /**
     * 等待下一个毫秒的到来
     *
     * @param lastTimestamp 上一次的时间戳
     * @return 下一个时间戳
     */
    private static long waitNextMillis(final long lastTimestamp) {
        long timestamp = System.currentTimeMillis();
        while (timestamp <= lastTimestamp) {
            timestamp = System.currentTimeMillis();
        }
        return timestamp;
    }

    /**
     * 生成指定长度的随机数字符串
     *
     * @param length 长度
     * @return 随机数字符串
     */
    private static String generateRandomPart(int length) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            sb.append((char) ('0' + Math.random() * 10));
        }
        return sb.toString();
    }
}
